package com.milotnt.controller;

import com.milotnt.pojo.Admin;
import com.milotnt.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    // 跳转到修改密码页面
    @GetMapping("/toUpdatePassword")
    public String toUpdatePassword(HttpSession session, Model model) {
        Admin admin = (Admin) session.getAttribute("admin");
        if (admin == null) {
            return "redirect:/admin/login"; // 未登录则跳转
        }
        model.addAttribute("admin", admin); // 关键！传递admin对象
        return "updateAdminPassword";
    }

    // 处理密码修改请求
    @PostMapping("/updatePassword")
    public String updateAdminPassword(
            @RequestParam String newPassword,
            @RequestParam String confirmPassword,
            HttpSession session,
            Model model) {

        // 1. 从Session获取当前管理员
        Admin admin = (Admin) session.getAttribute("admin");
        if (admin == null) {
            return "redirect:/admin/login";
        }

        // 2. 验证密码一致性
        if (!newPassword.equals(confirmPassword)) {
            model.addAttribute("msg", "两次密码输入不一致！");
            model.addAttribute("admin", admin); // 重新传入admin
            return "updateAdminPassword";
        }

        // 3. 更新密码（如需加密，这里调用加密方法）
        admin.setAdminPassword(newPassword);
        boolean result = adminService.updateAdminPassword(admin);

        // 4. 返回结果
        model.addAttribute("msg", result ? "密码修改成功！" : "密码修改失败！");
        model.addAttribute("admin", admin); // 重新传入admin
        return "updateAdminPassword";
    }
}